package com.cet.qz.unit01.chapter1_3;

import java.util.Iterator;

/**
 * @program: algorithm
 * @description:
 * @author: 陈恩涛
 * @create: 2021-04-08 20:37
 **/
public class CircleArrayQueueOfStrings implements Iterable<String> {

    private String[] a;
    private int first = 0; //队首
    private int last = 0; //队尾，数组实现的队列中，a[last]永远为空
    private int n; //队列中元素个数

    public CircleArrayQueueOfStrings(int size) {
        this.a = new String[size];
    }

    public int size() {
        return n;
    }

    public boolean isEmpty() {
        return first == last;
    }

    //牺牲一个存储空间来区分队满与队空
    public boolean isFull() {
        return (last + 1) % a.length == first;
    }

    public void enqueue(String s) {
        if (isFull()) {
            throw new RuntimeException("队列已满，请不要继续入队元素！");
        }
        a[last] = s;
        last = (last + 1) % a.length;
        n++;
    }

    public String dequeue() {
        if (isEmpty()) {
            throw new RuntimeException("队列为空！");
        }
        String s = a[first];
        a[first] = null;
        first = (first +1) % a.length;
        n--;
        return s;
    }

    @Override
    public Iterator<String> iterator() {
        return new ArrayIterator();
    }

    private class ArrayIterator implements Iterator<String> {

        private int front = first;
        private int rear = last;

        @Override
        public boolean hasNext() {
            return front != rear;
        }

        @Override
        public String next() {
            String s = a[front];
            front = (front + 1) % a.length;
            return s;
        }

        @Override
        public void remove() {

        }
    }


    public static void main(String[] args) {
        CircleArrayQueueOfStrings queue = new CircleArrayQueueOfStrings(5);
        queue.enqueue("a");
        queue.enqueue("b");
        queue.enqueue("c");
        queue.enqueue("d");
        System.out.println(queue.dequeue());
        queue.enqueue("e");
        System.out.println(queue.dequeue());
        queue.enqueue("f");
        for (String s : queue) {
            System.out.println(s);
        }
    }
}
